package com.lagou.client;


import com.lagou.common.GlobalStatic;
import com.lagou.handler.UserClientHandler;
import com.lagou.service.JSONSerializer;
import com.lagou.service.RpcDecoder;
import com.lagou.service.RpcEncoder;
import com.lagou.service.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消费者
 */
public class RPCConsumer {

    //1.创建一个线程池对象，它要处理我们自定义事件
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //2.声明一个自定义事件处理器 UserClientHandler
    private static UserClientHandler userClientHandler;

    //3.编写方法初始化客户端 （创建连接池，创建bootstrap 设置bootstrap 连接服务器）
    public static void initClient(String ip, int port) throws InterruptedException {
        //1.初始化UserClientHandler
        userClientHandler = new UserClientHandler();
        //2.创建连接池对象
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //1.获取管道对象
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                        pipeline.addLast("readtime",new ReadTimeoutHandler(5000));

                    }
                });
        //5. 连接服务端
        bootstrap.connect(ip,port).sync();
    }

    //4.编写一个方法，使用JDK的动态代理创建对象
    //serviceClass 接口类型，根据哪个接口生成自雷代理对象；providerParam："UserService#sayHello#"
    public static Object createProxy(final Class<?> serviceClass, final String providerParam,CuratorFramework client ) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //随机获取
                        String[] keys = GlobalStatic.servers.keySet().toArray(new String[0]);
                        Random random = new Random();
                        String randomKey = keys[random.nextInt(keys.length)];
                        String server = GlobalStatic.servers.get(randomKey);
                        //1.初始化客户端client
                        if (userClientHandler == null) {
                            initClient(randomKey.split(":")[0], Integer.valueOf(randomKey.split(":")[1]));
                        }
                        System.out.println("ip:"+randomKey.split(":")[0]+" port:"+Integer.valueOf(randomKey.split(":")[1]));
                        //封装RpcRequest
                        RpcRequest rpcRequest = new RpcRequest();
                        String className = providerParam.substring(0, providerParam.indexOf("#"));
                        rpcRequest.setClassName(className);
                        String methodName = method.getName();
                        rpcRequest.setMethodName(methodName);
                        rpcRequest.setParameters(args);
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        //2.给UserClientHandler设置param参数
                        //userClientHandler.setParam(providerParam+args[0]);
                        userClientHandler.setRpcRequest(rpcRequest);
                        //3.使用线程池，开启一个线程处理call()写操作，并返回结果
                        long currentTime =System.currentTimeMillis();
                        Object result = executorService.submit(userClientHandler).get();
                        long time = System.currentTimeMillis()-currentTime;
                        client.setData().forPath("/provide/"+randomKey,(time+"").getBytes());
                        System.out.println(result);
                        //4.return结果
                        return result;
                    }
                });
    }
}
